package com.sun.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.dao.*;
import com.sun.pojo.*;
import com.sun.service.CheckinService;
import com.sun.service.CheckoutService;
import com.sun.utils.DataGridViewResult;
import com.sun.utils.SystemConstant;
import com.sun.utils.UUIDutiles;
import com.sun.vo.CheckinVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CheckoutServiceImpl implements CheckoutService {

    @Autowired
    private CheckinMapper checkinMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private RoomTypeMapper roomTypeMapper;
    @Autowired
    private RoomMapper roomMapper;

    @Autowired
    private CheckoutMapper checkoutMapper;

    @Transactional(rollbackFor = RuntimeException.class)
    public int addCheckout(int checkinid,int price,int loginUserId) {
        Checkout checkout = new Checkout();
        checkout.setCheckOutNumber(UUIDutiles.getUuid());
        checkout.setCheckInId((long) checkinid);
        checkout.setConsumePrice((double) price);
        checkout.setCreateDate(new Date());
        checkout.setCreatedBy(loginUserId);
        checkout.setRemark(SystemConstant.CHECKOUT_MESSAGE);
        // 1 添加退房记录
        int addCheckoutResult=checkoutMapper.addCheckout(checkout);

        if(addCheckoutResult>0){
            // 5 修改入住记录状态
            Checkin checkin= checkinMapper.findById(checkinid);
            checkin.setStatus(SystemConstant.CHECK_IN_STATUS_2);
            int updateCheckinResult=checkinMapper.updateCheckin(checkin);
            // 2 修改订单状态
            Orders orders=new Orders();
            orders.setId(checkin.getOrdersid());
            orders.setStatus(SystemConstant.ORDERS_STATUS_4);
            int updateOrdersResult = ordersMapper.updateOrders(orders);
            // 3 修改房间状态为可预订
            Room room = roomMapper.findOne(checkin.getRoomid());
            room.setStatus(SystemConstant.ROOM_STATUS_3);
            int updateRoomResult = roomMapper.updateRoom(room);
            // 4 修改房型 可入住+1 已入住-1
            RoomType roomType = roomTypeMapper.findById(checkin.getRoomtypeid());
            roomType.setLivednum(roomType.getLivednum()-1);
            roomType.setAvilablenum(roomType.getAvilablenum()+1);
            if(roomType.getRoomnum()>roomType.getLivednum()){
                roomType.setStatus(SystemConstant.ROOM_TYPE_STATUS_1);
            }
            int updateRoomTypeResult = roomTypeMapper.updateRoomType(roomType);
            if(updateCheckinResult>0 && updateOrdersResult>0 && updateRoomResult>0 && updateRoomTypeResult>0){
                return 1;
            }
        }
        return 0;
    }
}
